/**

 * @param {*} fn 
 * @param {*} delay 
 * @returns 
 */
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

/**
 * 这个是开始执行，然后过了delay后触发才再次执行，和throttling效果一样
 * @param {*} fn
 * @param {*} delay
 * @param {boolean} immediate
 * @returns
 */
function debounceX(fn, delay, immediate) {
  let timer = null;

  return function (...args) {
    // 第一次执行
    if (!timer && immediate) {
      fn.apply(this, args);
    }

    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    timer = setTimeout(() => {
      // 执行完置空
      if (immediate) {
        timer = null;
      } else {
        fn.apply(this, args);
      }
    }, delay);
  };
}
